﻿using CrawlerApp.Infrastructure.Interfaces;
using System.Threading.Tasks;
using StackExchange.Profiling;
using Autofac;
using CrawlerApp.Infrastructure.Enums;
using System.Diagnostics;

namespace CrawlerApp.Services.Interceptors.Events
{
    public interface IInterceptorEventHandler<in TIntegrationEvent> : IIntegrationEventHandler
    {
        Task Handler(TIntegrationEvent @event);
    }

    public class InterceptorEventHandler : IInterceptorEventHandler<InterceptorEvent>
    {
        private readonly ILifetimeScope scope;
        private MiniProfiler profiler;
        public InterceptorEventHandler(ILifetimeScope scope)
        {
            this.scope = scope;
        }

        public async Task Handler(InterceptorEvent @event)
        {
            if(@event.Type == InterceptorEventType.Before)
            {
                profiler = MiniProfiler.StartNew();
                using (profiler.Step("interceptor enter")) { }
            }
            if(@event.Type == InterceptorEventType.After)
            {
                using (profiler.Step("interceptor out"))
                {
                    Trace.WriteLine(profiler.RenderPlainText());
                }
                await profiler.StopAsync();
            }
        }
    }
}
